package com.langsin.my0628;

import com.langsin.bean.User;
import com.langsin.shixu.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;

/**
 * @author ShixuTest
 * @version 1.0
 * @since 2022/6/28
 */
public class ShixuTest {

    @Test
    // 一级 缓存测试    如果同一个会话对象 进行了 增删改 ,缓存就会失效.
    public void testLevelOneCache() throws Exception {
        // mybatis一级缓存是 存在 sqlSession的 内存 map里的 .
        InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = builder.build(inputStream);
        SqlSession sqlSession = build.openSession();

        //查询第一次  ————从同一个sqlSession对话
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.queryById(701);
        System.out.println("查询第一次: " +user);

        Thread.sleep(2000); //休眠两秒钟

        User user1 = userMapper.queryById(701);
        System.out.println("查询第二次: " +user);
    }


    @Test
    // 二级 缓存测试   ————不同的对话 之间的 缓存
    //需要 我们的对象 能 序列化   , 二级缓存 有可能存入到硬盘里的.
    public void testLevelTwoCache() throws Exception {
        InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(inputStream);

        // 第一个会话的查询
        SqlSession sqlSession1 = sessionFactory.openSession();
        UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = userMapper1.queryById(701);
        System.out.println("查询第一次: " +user1);
        sqlSession1.close();

        Thread.sleep(2000); //休眠两秒钟

        // 第二个会话的查询
        SqlSession sqlSession2 = sessionFactory.openSession();
        UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = userMapper2.queryById(701);
        System.out.println("查询第二次: " +user2);
        sqlSession2.close();
    }
}
